﻿-- Batch submitted through debugger: SQLQuery1.sql|0|0|C:\Users\Nacho\AppData\Local\Temp\~vsDE4B.sql
CREATE PROCEDURE [ExecuteStatement]
	@StockName nvarchar(128),
	@Statement nvarchar(max)
AS
BEGIN
	DECLARE @TableName sysname

	DECLARE TableNameCursor CURSOR FOR
	SELECT TableName FROM dbo.QuotationTables WHERE IdStock IN (SELECT Id FROM dbo.Stocks WHERE Name LIKE @StockName)

	OPEN TableNameCursor
	FETCH NEXT FROM TableNameCursor INTO @TableName

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @Query nvarchar(max)
		SET @Query = REPLACE(@Statement,'{x}',@TableName)
		EXEC sp_executesql @Query

		-- This is executed as long as the previous fetch succeeds.
		FETCH NEXT FROM TableNameCursor INTO @TableName
	END
END